package com.myjoje.service;

import com.myjoje.bean.system.UserBean;
import com.myjoje.service.system.UserService;
import com.myjoje.util.Message;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PubService {

    @Autowired
    private UserService userService;

    public Message validatePrincipal(String username, String password) {
        try {
            //判断是否是微信登录
            UserBean bean = userService.getUserByPrincipal(username);
            if (null != bean) {
                UsernamePasswordToken token;
                if (username.equals(bean.getOpenid())) {
                    token = new UsernamePasswordToken(username, "123");
                } else {
                    token = new UsernamePasswordToken(username, password);
                }
                //登录
                Subject subject = SecurityUtils.getSubject();
                subject.login(token);
                return Message.success("登录成功", subject.getSession().getId());
            } else {
                return Message.error("用户名不存在");
            }
        } catch (UnknownAccountException uae) {
            return Message.error("用户名不存在");
        } catch (IncorrectCredentialsException ice) {
            return Message.error("密码错误");
        } catch (LockedAccountException lae) {
            return Message.error("账号锁定");
        } catch (Exception e) {
            e.printStackTrace();
            return Message.error("账号或密码错误，请重新登录");
        }
    }
}
